<template>
    <div class="quiz-container">
        <!-- 问题栏 -->
        <div class="question-card">
            <h2>{{ questions[currentQuestion].question }}</h2>
            <div class="options">
                <button v-for="(option, index) in questions[currentQuestion].options" :key="index" class="option-btn"
                    :class="{ selected: answers[currentQuestion] === index }" @click="selectOption(index)">
                    {{ option }}
                </button>
            </div>
        </div>

        <!-- 导航按钮 -->
        <div class="navigation-buttons">
            <button class="nav-btn" :disabled="currentQuestion === 0" @click="prevQuestion">
                上一题
            </button>
            <button class="nav-btn" @click="nextQuestion">
                {{ currentQuestion === questions.length - 1 ? "提交" : "下一题" }}
            </button>
        </div>
        <div v-if="showResult" class="modal-overlay" @click.self="closeModal">
      <div class="modal">
        <h2>测验结果</h2>
        <p>您的分数是：{{ score }}%</p>
        <div class="detailed-results">
          <div v-for="(q, index) in questions" :key="index">
            <p>
              第{{ index + 1 }}题: 您的答案是“{{ getAnswerText(index) }}”，正确答案是“{{ q.options[q.correctAnswer] }}”。
            </p>
          </div>
        </div>
        <button class="close-btn" @click="closeModal">返回页面</button>
      </div>
    </div>
    </div>
</template>

<script>
import request from '@/utils/request';

export default {
    data() {
        return {
            postId: 1,
            currentQuestion: 0, // 当前题目索引
            answers: [], // 保存用户选择的答案
            questions: [], // 存储从后端获取的问题
            showResult: false,
            score: 0,
        };
    },
    created() {
        this.postId = this.$route.query.id;
    },
    mounted() {
        // 请求后端获取问题数据
        console.log(this.postId);

        request.get(`/questions/post/${this.postId}`)
            .then(response => {
                if (response.code === 200) {
                    // 转换后端数据为前端要求的格式
                    this.questions = response.data.map(item => ({
                        id: item.id,
                        question: item.question, // 题目内容
                        options: JSON.parse(item.options), // 解析 options 字符串为数组
                        correctAnswer: item.correctAnswer // 正确答案索引
                    }));
                } else {
                    console.error("查询失败:", response.msg);
                }
            })
            .catch(error => {
                console.error("获取题目数据失败", error);
            });


    },
    methods: {
        // 保存用户选择的选项
        selectOption(index) {
            this.$set(this.answers, this.currentQuestion, index);
        },
        // 跳转到上一题
        prevQuestion() {
            if (this.currentQuestion > 0) {
                this.currentQuestion--;
            }
        },
        // 跳转到下一题或提交
        nextQuestion() {
            if (this.currentQuestion < this.questions.length - 1) {
                this.currentQuestion++;
            } else {
                this.submitQuiz();
            }
        },
        // 提交测验并显示分数
        submitQuiz() {
            const totalQuestions = this.questions.length;
            let correctCount = 0;

            // 计算正确答案数量，并记录错题
            this.questions.forEach((q, index) => {
                if (this.answers[index] === q.correctAnswer) {
                    correctCount++;
                } else {
                    request.post('/incorrectQuestions', {
                        questionId: q.id, // 假设每个问题有唯一的 id
                        userId: JSON.parse(localStorage.getItem('userInfo')).id,
                    })
                        .then(response => {
                            console.log("错题已提交", response);
                        })
                        .catch(error => {
                            console.error("提交错题失败", error);
                        });
                }
            });

            // 显示结果
            const score = ((correctCount / totalQuestions) * 100).toFixed(2);
            let resultMessage = `您的分数是：${score}\n\n详细结果：\n`;

            this.questions.forEach((q, index) => {
                const userAnswer = this.answers[index] !== undefined ? q.options[this.answers[index]] : "未作答";
                const correctAnswer = q.options[q.correctAnswer];
                resultMessage += `第${index + 1}题: 您的答案是“${userAnswer}”，正确答案是“${correctAnswer}”。\n`;
            });

            this.score = ((correctCount / totalQuestions) * 100).toFixed(2);
      this.showResult = true;


        },
        closeModal() {
            try {
                window.close(); // 尝试关闭页面
            } catch (error) {
                console.error("无法关闭页面，可能是因为浏览器限制。");
            }
        },
        getAnswerText(index) {
            return this.answers[index] !== undefined
                ? this.questions[index].options[this.answers[index]]
                : "未作答";
        },
    }
};
</script>


<style scoped>
/* 页面布局 */
.quiz-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    background-color: #f9f9f9;
    font-family: Arial, sans-serif;
}

/* 问题卡片 */
.question-card {
    background-color: #ffffff;
    padding: 20px 30px;
    width: 80%;
    max-width: 500px;
    border-radius: 12px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    text-align: center;
    margin-bottom: 20px;
}

.question-card h2 {
    font-size: 18px;
    margin-bottom: 20px;
    color: #333333;
}

/* 选项按钮 */
.options {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.option-btn {
    padding: 12px;
    font-size: 16px;
    border: 2px solid #d1d1d1;
    background-color: #f3f3f3;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s;
}

.option-btn:hover {
    background-color: #e6f7ff;
    border-color: #1890ff;
}

.option-btn.selected {
    background-color: #1890ff;
    color: #ffffff;
    border-color: #0077cc;
}

/* 导航按钮 */
.navigation-buttons {
    display: flex;
    justify-content: space-between;
    width: 80%;
    max-width: 500px;
}

.nav-btn {
    padding: 10px 20px;
    font-size: 16px;
    background-color: #4caf50;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s;
}

.nav-btn:disabled {
    background-color: #9e9e9e;
    cursor: not-allowed;
}

.nav-btn:hover:not(:disabled) {
    background-color: #45a049;
}

.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
}

.modal {
    background: white;
    padding: 20px;
    border-radius: 5px;
    max-width: 500px;
    width: 100%;
    text-align: center;
}

.close-btn {
  margin-top: 20px;
  padding: 10px 20px;
  font-size: 16px;
  color: #fff;
  background-color: #dc3545;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.close-btn:hover {
  background-color: #b02a37;
}
</style>